import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime, timedelta

def format_number(value, unit=''):
    """格式化数字显示，添加千位分隔符"""
    if pd.isna(value):
        return '-'
    if isinstance(value, (int, float)):
        if value >= 100000000:  # 亿
            return f"{value/100000000:.2f}亿{unit}"
        elif value >= 10000:  # 万
            return f"{value/10000:.2f}万{unit}"
        else:
            return f"{value:.2f}{unit}"
    return str(value)

def create_candlestick_chart(data, title='K线图'):
    """创建K线图
    
    Args:
        data: 包含OHLC数据的DataFrame
        title: 图表标题
        
    Returns:
        plotly图表对象
    """
    fig = go.Figure(data=[go.Candlestick(
        x=data.index if isinstance(data.index, pd.DatetimeIndex) else data['trade_date'],
        open=data['open'],
        high=data['high'],
        low=data['low'],
        close=data['close'],
        increasing_line_color='red',  # 中国股市上涨为红色
        decreasing_line_color='green'  # 中国股市下跌为绿色
    )])
    
    fig.update_layout(
        title=title,
        xaxis_title='日期',
        yaxis_title='价格',
        xaxis_rangeslider_visible=False,
        height=500
    )
    
    return fig

def calculate_technical_indicators(data):
    """计算常用技术指标
    
    Args:
        data: 包含OHLC数据的DataFrame
        
    Returns:
        添加了技术指标的DataFrame
    """
    df = data.copy()
    
    # 确保数据按日期排序
    if 'trade_date' in df.columns:
        df = df.sort_values('trade_date')
    
    # 计算移动平均线
    df['MA5'] = df['close'].rolling(window=5).mean()
    df['MA10'] = df['close'].rolling(window=10).mean()
    df['MA20'] = df['close'].rolling(window=20).mean()
    
    # 计算MACD
    df['EMA12'] = df['close'].ewm(span=12, adjust=False).mean()
    df['EMA26'] = df['close'].ewm(span=26, adjust=False).mean()
    df['MACD'] = df['EMA12'] - df['EMA26']
    df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
    df['Histogram'] = df['MACD'] - df['Signal']
    
    # 计算RSI
    delta = df['close'].diff()
    gain = delta.where(delta > 0, 0)
    loss = -delta.where(delta < 0, 0)
    
    avg_gain = gain.rolling(window=14).mean()
    avg_loss = loss.rolling(window=14).mean()
    
    rs = avg_gain / avg_loss
    df['RSI'] = 100 - (100 / (1 + rs))
    
    return df

def get_market_summary(stock_manager):
    """获取市场概览数据
    
    Args:
        stock_manager: StockDataManager实例
        
    Returns:
        市场概览数据字典
    """
    try:
        # 获取最近的交易日
        latest_trade_date = stock_manager.get_trade_date(offset=0)
        
        # 获取上证指数数据
        index_data = stock_manager.pro.index_daily(ts_code='000001.SH', trade_date=latest_trade_date)
        
        if index_data.empty:
            return {
                'trade_date': datetime.now().strftime('%Y-%m-%d'),
                'index_change': 0,
                'index_change_percent': 0,
                'total_stocks': 0,
                'up_stocks': 0,
                'down_stocks': 0,
                'flat_stocks': 0
            }
        
        # 获取当日所有股票数据
        daily_data = stock_manager.get_daily_data(latest_trade_date)
        
        # 计算上涨、下跌、平盘股票数量
        up_stocks = len(daily_data[daily_data['pct_chg'] > 0])
        down_stocks = len(daily_data[daily_data['pct_chg'] < 0])
        flat_stocks = len(daily_data[daily_data['pct_chg'] == 0])
        
        # 格式化日期
        trade_date = datetime.strptime(latest_trade_date, '%Y%m%d').strftime('%Y-%m-%d')
        
        return {
            'trade_date': trade_date,
            'index_change': index_data['change'].values[0] if not index_data.empty else 0,
            'index_change_percent': index_data['pct_chg'].values[0] if not index_data.empty else 0,
            'total_stocks': len(daily_data),
            'up_stocks': up_stocks,
            'down_stocks': down_stocks,
            'flat_stocks': flat_stocks
        }
    except Exception as e:
        print(f"获取市场概览数据出错: {str(e)}")
        return {
            'trade_date': datetime.now().strftime('%Y-%m-%d'),
            'index_change': 0,
            'index_change_percent': 0,
            'total_stocks': 0,
            'up_stocks': 0,
            'down_stocks': 0,
            'flat_stocks': 0
        }
